package logweb

import (
	"container/list"
	"encoding/json"
	"net/http"
	"strconv"
	"sync"
	"time"

	"gitee.com/haodreams/golib/logs"
)

var l = WebWriter{
	Level:    int(logs.LevelDebug),
	MaxLines: 300,
	msgList:  list.New(),
}

// Rows 记录集
type Rows struct {
	Count int    `json:"count"`
	Rows  []*Row `json:"data"`
	Code  int    `json:"code"` //兼容layui
	Msg   string `json:"msg"`  //兼容layui
}

// Row 记录
type Row struct {
	Time  int64
	Msg   string
	Level int
}

// WebWriter web 日志类
type WebWriter struct {
	sync.RWMutex     // write log order by order and  atomic incr maxLinesCurLines and maxSizeCurSize
	MaxLines     int `json:"maxlines"`
	Level        int `json:"level"`
	msgList      *list.List
}

// Page 查询指定的页数据
func Page(page, limit int) ([]*Row, int) {
	pos := (page - 1) * limit
	rows := make([]*Row, limit)
	end := pos + limit

	i := 0
	idx := 0
	l.RLock()
	//log.Println("rlock", l.msgList.Len())
	total := l.msgList.Len()
	for e := l.msgList.Front(); e != nil; e = e.Next() {
		idx++
		//log.Println(idx, pos, limit, i)
		if idx > pos && i < end {
			rows[i], _ = e.Value.(*Row)
			i++
			if i >= limit {
				break
			}
		}
	}
	//log.Println("runlock1")
	l.RUnlock()
	//log.Println("runlock")

	return rows[:i], total
}

// HTTPLogs http 请求日志
func HTTPLogs(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	pos := 0
	limit := 100
	s := r.FormValue("rows")
	if s != "" {
		li, err := strconv.Atoi(s)
		if err == nil {
			limit = li
		}
	}

	s = r.FormValue("page")
	if s != "" {
		st, err := strconv.Atoi(s)
		if err == nil {
			pos = (st - 1) * limit
		}
	}

	msg := new(Rows)
	rows := make([]*Row, limit)

	i := 0
	idx := 0
	l.RLock()
	msg.Code = 200
	msg.Count = l.msgList.Len()
	for e := l.msgList.Front(); e != nil; e = e.Next() {
		idx++
		if idx > pos && i < limit {
			rows[i], _ = e.Value.(*Row)
			i++
		}
		if i >= limit {
			break
		}
	}
	l.RUnlock()
	msg.Rows = rows[:i]
	data, _ := json.Marshal(msg)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(data)
}

func init() {
	//logs.Register("weblog", NewWebWriter)
	logs.SetLogger("weblog")
}

//NewWebWriter 创建日志
// func NewWebWriter() logs.Logger {
// 	return &l
// }

// Init 初始化
func (lw *WebWriter) Init(config string) (err error) {
	if config == "" {
		return
	}
	err = json.Unmarshal([]byte(config), lw)
	if err != nil {
		return err
	}
	return
}

// WriteMsg 写入一个消息
func (lw *WebWriter) WriteMsg(when time.Time, msg string, level int) (err error) {
	if level > lw.Level {
		return nil
	}
	var m *Row

	lw.Lock()
	//log.Println("lock")
	if lw.msgList.Len() >= lw.MaxLines {
		var ok bool
		elem := lw.msgList.Back()
		lw.msgList.Remove(elem)
		//循环利用
		if m, ok = elem.Value.(*Row); !ok {
			m = new(Row)
		}
	} else {
		m = new(Row)
	}
	m.Time = when.Unix()
	m.Level = level
	m.Msg = msg
	lw.msgList.PushFront(m)
	lw.Unlock()
	//log.Println("unlock")

	return
}

// Destroy 空实现
func (lw *WebWriter) Destroy() {}

// Flush 空实现
func (lw *WebWriter) Flush() {}
